package com.petter.lock.juc.countdownLatch;

/**
 * @author : GD
 * @date :2021/12/21 : 22:46
 */
public class NotifyForThread {
    public static void main(String[] args) {
        Object lock = new Object();
        // 线程1 获取到锁后，wait 就释放锁。
        // 线程2 获取锁，执行到5 的时候，通知并释放锁
        // 线程1 获取锁执行我完毕，通知释放锁
        // 线程2 获取锁并执行完毕

        new Thread(new NotifyThread1(lock)).start();
        new Thread(new NotifyThread2(lock,5)).start();

    }
}
class NotifyThread1 implements Runnable{
    Object lock ;

    public NotifyThread1(Object lock) {
        this.lock = lock;
    }
    @Override
    public void run() {
        synchronized (lock){
            try {
                System.out.println("t1 is start");
                lock.wait();
                System.out.println("t1 is down");
                lock.notify();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
class NotifyThread2 implements Runnable{
    Object lock ;
    int count ;
    public NotifyThread2(Object lock,int count) {
        this.count = count ;
        this.lock = lock;
    }

    @Override
    public void run() {
        synchronized (lock) {
            for (int i = 0; i < 10; i++) {
                try {
                    if (i == count) {
                        lock.notify();
                        //释放锁后，会进入一个争抢资源状态
                        lock.wait();
                    }
                    Thread.sleep(500);
                    System.out.println("t2 i " + i);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
